﻿using System;
using NHibernate.Event;
using NHibernate.Id;
using Domain.Model.Commons;
using NHibernate.Id.Insert;
using NHibernate.Engine;
using Common.Logging;
using NHibernate.Event.Default;

namespace Domain.Repository
{
	public class SaveOrUpdateEventListener : DefaultSaveEventListener
	{
		protected static ILog logger = LogManager.GetLogger(typeof(SaveOrUpdateEventListener));

		protected override object PerformSaveOrUpdate(SaveOrUpdateEvent @event)
		{
			GuidCombGenerator generator = new GuidCombGenerator();
			var component = @event.Entity as AbstractComponent;
			if (null != component && String.IsNullOrWhiteSpace(component.Id))
			{
				component.Id = generator.Generate(@event.Session, component).ToString().Replace("-", String.Empty);
			}
			var entity = @event.Entity as AbstractEntity;
			if (null != entity && String.IsNullOrWhiteSpace(entity.Id))
			{
				entity.Id = generator.Generate(@event.Session, entity).ToString().Replace("-", String.Empty);

			}
			var dict = @event.Entity as AbstractDictEntity;
			if (null != dict && String.IsNullOrWhiteSpace(dict.Id))
			{
				dict.Id = generator.Generate(@event.Session, dict).ToString().Replace("-", String.Empty);
			}

			return base.PerformSaveOrUpdate(@event);
		}
	}
}
